

package com.yq.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Simple to Introduction
 * className: MyCounter
 *
 * @author EricYang
 * @version 2018/5/8 19:32
 */
public class MyCounterV2 {
    public final static Map<String, AtomicLong> aMap = new HashMap();

    public static synchronized void increaseA(String key, int increase) {
        System.out.println("AThreadId:"+ Thread.currentThread().getId() + " :" + System.currentTimeMillis());
        AtomicLong counter = aMap.get(key);
        if (counter == null) {
            counter = new AtomicLong(0);
            aMap.put(key, counter);
        }

        counter.addAndGet(increase);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
/*
sleep不会释放锁的
当两个map分别位于MyCounter和MyCounterV2中， MyRunnableA访问MyCounterV2的increase方法。 MyRunnableB访问MyCounter中的increase方法
多个线程几乎可以同时调用increase方法，也就是同时访问了两个map。 从数据看

BThreadId:13 :1525827766481  线程13访问了MyCounterV的bMap，   时间1525827766481
AThreadId:12 :1525827766481  线程12访问了MyCounterV2的aMap ， 时间1525827766481  也就是同时访问了aMap和bMap
BThreadId:29 :1525827768482
AThreadId:28 :1525827768482
AThreadId:30 :1525827770482
BThreadId:21 :1525827770482
AThreadId:26 :1525827772483
BThreadId:27 :1525827772483
AThreadId:16 :1525827774483
BThreadId:23 :1525827774483
BThreadId:19 :1525827776484
AThreadId:24 :1525827776484
BThreadId:15 :1525827778485
。。。。
 */